<template>
  <div style="height: 100%; margin-left: 10px; position: relative; z-index: 20;">
    <div class="lamp-btn-box">
      <div class="lamp-btn" v-for="(item,idx) in lampData"
           @click="lampHandle(item,idx)"
           :class="{'on': lampIdx == idx}">
        {{ item.towername || item.brigename }}
      </div>
    </div>
    <div class="date-box">
      <div class="date-btn-box">
        <div class="def-btn" v-for="(item,idx) in dateBtn"
             @click="dateHandle(item,idx)"
             :class="{'on-btn': dateIdx == idx}">
          {{ item.name }}
        </div>
        <div>
          <label>时间：</label>
<!--          <el-date-picker
              v-if="dateIdx == 0"
              v-model="year"
              type="year"
              placeholder="请选择"
          />-->
          <el-date-picker
              v-if="dateIdx == 0"
              v-model="year"
              type="monthrange"
              range-separator="~"
              start-placeholder="起始月"
              end-placeholder="终止月"
              format="YYYY-MM"
              value-format="YYYY-MM"
              @change="getEchartsData"
          />
          <el-date-picker
              v-if="dateIdx == 1"
              v-model="month"
              type="daterange"
              popper-class="energy-time"
              range-separator="~"
              start-placeholder="起始时间"
              end-placeholder="终止时间"
              value-format="YYYY-MM-DD"
              @change="getEchartsData"
          >
            <template #default="cell">
              <div class="cell" :class="{ current: cell.isCurrent }">
                <div class="text">{{ cell.text }}</div>
                <div v-if="isHoliday(cell)" class="holiday">
                  <label>{{ getDayVal(cell) }}</label>
                </div>
              </div>
            </template>
          </el-date-picker>
          <el-date-picker
              v-if="dateIdx == 2"
              v-model="dateMonth"
              type="datetimerange"
              popper-class="energy-time"
              range-separator="~"
              start-placeholder="起始时间"
              end-placeholder="终止时间"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
              @change="getEchartsData"
          >
            <template #default="cell">
              <div class="cell" :class="{ current: cell.isCurrent }">
                <div class="text">{{ cell.text }}</div>
                <div v-if="isHoliday(cell)" class="holiday">
                  <label>{{ getDayVal(cell) }}</label>
                </div>
              </div>
            </template>
          </el-date-picker>
        </div>
      </div>
      <div class="r-btn" v-if="userInfo.role != 3">
        <div class="sure-btn down-btn" @click="downLoadExcel">导出</div>
      </div>
<!--      <div class="r-btn">
        <div class="def-btn" v-for="(item,idx) in rBtn"
             @click="rBtnHandle(item,idx)"
             :class="{'on-btn': rIdx == idx}">
          {{ item.name }}
        </div>
      </div>-->
    </div>
    <div class="echarts-box">
      <div class="name">
        <img src="@/assets/images/img-icon15.svg"/>
        <div>{{ currentLamp.towername || currentLamp.brigename }}
          <template v-if="year">{{ year[0] }} ~ {{ year[1] }}</template>
          <template v-if="month">{{ month[0] }} ~ {{ month[1] }}</template>
          <template v-if="dateMonth">{{ dateMonth[0] }} ~ {{ dateMonth[1] }}</template>
          总用电量</div>
      </div>
      <line-echarts :echartsData="echartsData" :unit="unit" yUnit="千瓦时" pageName="reportManagement"></line-echarts>
    </div>
  </div>
</template>
<script>
import LineEcharts from "./lineEcharts.vue";
import {
  BrigeZongLan, EnergyGet,
  judgeLightOnline,
  MonthEnergyGet,
  refreshGatewayData,
  TowerZongLan,
  YearEnergyGet,
  DayEnergyGet, exportYearEnergy
} from "../../router/api.js";
import {mapGetters} from "vuex";
import {downBlobFile, downloadFile, getNowFormatDate, subtractDay, subtractMonths} from "../../util/index.js";

export default {
  components: {LineEcharts},
  computed: {
    ...mapGetters(['currentNav','userInfo'])
  },
  data() {
    return {
      lampIdx: 0,
      dateBtn: [
        {name: '年报表'},
        {name: '月报表'},
        // {name: '周报表'},
        {name: '日报表'},
      ],
      dateIdx: 2,
      year: [],
      month: [],
      dateMonth: [],
      startTimeStr: '',
      endTimeStr: '',
      buildingName: '',
      rBtn: [
        {name: '同比'},
        {name: '环比'},
      ],
      rIdx: 0,
      lampData: [],
      echartsData: [],
      unit: '日',
      currentLamp: {},
      holidays: [],
      holidaysList: {
        // '2025-07-01': '5.69',
        // '2025-07-02': '5.68',
        // '2025-07-03': '5.67',
        // '2025-07-04': '5.66',
        // '2025-07-05': '5.65',
        // '2025-07-06': '5.64',
        // '2025-07-07': '5.63',
      }
    };
  },
  watch:{
    'currentNav': {
      deep: true,
      handler(){
        this.lampIdx = 0;
        this.getLampData()
      }
    }
  },
  created() {
    this.getLampData();
  },
  methods: {
    getEchartsData(){
      if(!this.lampData.length) return;
      let val = this.lampData[this.lampIdx];
      let buildingName = val.towername || val.brigename;
      this.buildingName = buildingName;

      if(this.lampIdx == 0){
        switch (this.currentNav){
          case 0:
            buildingName = '全区域汇总'
              break;
          case 1:
            buildingName = '一区汇总'
            break;
          case 2:
            buildingName = '二区汇总'
            break;
          case 3:
            buildingName = '三区汇总'
            break;
        }
      }

      if(this.dateIdx == 0){
        this.yearEnergyGetHandle(buildingName)
      }else if(this.dateIdx == 1){
        this.monthEnergyGethandle(buildingName);
      }else{
        this.energyGetHandle(buildingName)
      }
    },
    async getLampData() {
      let resLamp = await TowerZongLan();
      let resLampBridge = await BrigeZongLan()
      let lighthouse = [], lampBridge = [];
      if (resLamp.data.code == 200) {
        lighthouse = JSON.parse(JSON.stringify(resLamp.data.data)).filter(opt => opt.towerArea == this.currentNav);
      }else{
        this.$message.warning('无法请求服务器资源，请确认服务器是否开启')
      }
      if (resLampBridge.data.code == 200) {
        lampBridge = JSON.parse(JSON.stringify(resLampBridge.data.data)).filter(opt => opt.brigeArea == this.currentNav);
      }
      this.lampData = [...lighthouse,...lampBridge];
      this.lampData.sort((a,b) => a.locationUi - b.locationUi)
      this.lampData.unshift({ towername:'总览', id: -1 })
      /*this.lampData = [{ towername:'总览', id: -1 }, ...lighthouse];
      if (this.lampData.length >= 3) {
        this.lampData.splice(3, 0, ...lampBridge)
      } else {
        this.lampData.push(...lampBridge)
      }*/
      this.currentLamp = this.lampData[0]

      this.getEchartsData();
    },
    yearEnergyGetHandle(buildingName){
      let startTimeStr = '', endTimeStr = '';
      if(this.month){
        startTimeStr = this.month[0];
        endTimeStr = this.month[1];
      }else{
        let nowDate = getNowFormatDate();
        const fiveMonthsAgo = subtractMonths(new Date(), 5);
        startTimeStr = fiveMonthsAgo.ym;
        endTimeStr = nowDate.ym;
      }
      this.startTimeStr = startTimeStr;
      this.endTimeStr = endTimeStr;
      this.year = [startTimeStr,endTimeStr];
      YearEnergyGet({ buildingName,
        startTimeStr: startTimeStr +'-01 00:00:00',
        endTimeStr: endTimeStr +'-01 00:00:00',}).then(res => {
        if(res.data.code == 200){
          this.echartsData = JSON.parse(res.data.data);
          // this.$message.success(res.data.msg)
        }else{
          // this.$message.warning(res.data.msg)
        }
      })
    },
    monthEnergyGethandle(buildingName){
      let startTimeStr = '', endTimeStr = '';
      if(this.month){
        startTimeStr = this.month[0];
        endTimeStr = this.month[1];
      }else{
        let nowDate = getNowFormatDate();
        const fiveMonthsAgo = subtractMonths(new Date(), 5);
        startTimeStr = fiveMonthsAgo.ymd;
        endTimeStr = nowDate.ymd;
      }
      this.startTimeStr = startTimeStr;
      this.endTimeStr = endTimeStr;
      this.month = [startTimeStr,endTimeStr]

      MonthEnergyGet({ buildingName,
        startTimeStr: startTimeStr +' 00:00:00',
        endTimeStr: endTimeStr +' 00:00:00',
      } ).then(res => {
        if(res.data.code == 200){
          this.echartsData = JSON.parse(res.data.data);
          // this.$message.success(res.data.msg)
        }else{
          // this.$message.warning(res.data.msg)
        }
      })
    },
    energyGetHandle(buildingName){
      let startTimeStr = '', endTimeStr = '';
      if(this.dateMonth.length){
        startTimeStr = this.dateMonth[0];
        endTimeStr = this.dateMonth[1];
      }else{
        let nowDate = getNowFormatDate();
        let oldDate = subtractDay(7);
        endTimeStr = nowDate.ymd +' 12:00:00';
        startTimeStr = oldDate.ymd +' 12:00:00';
      }
      this.startTimeStr = startTimeStr;
      this.endTimeStr = endTimeStr;
      this.dateMonth = [startTimeStr,endTimeStr]
      DayEnergyGet({ buildingName, startTimeStr, endTimeStr} ).then(res => {
        if(res.data.code == 200){
          this.echartsData = res.data.data;

          this.setDayData(this.echartsData);
          // this.$message.success(res.data.msg)
        }else{
          // this.$message.warning(res.data.msg)
        }
      })
    },
    setDayData(data){
      data.forEach(opt => {
        let time = opt.createtime.split(' ')[0];
        this.holidays.push(time);
        if(!this.holidaysList[time]){
          this.holidaysList[time] = opt.energyConsumption
        }
      })
      console.log(this.holidaysList)
    },
    lampHandle(item, idx) {
      this.currentLamp = item;
      this.lampIdx = idx;
      this.getEchartsData();
    },
    dateHandle(item, idx) {
      this.year = '';
      this.month = '';
      this.dateMonth = '';
      this.dateIdx = idx;
      if(idx == 0){
        this.unit = '年'
      }else if(idx == 1){
        this.unit = '月'
      }else{
        this.unit = '日'
      }

      this.getEchartsData();
    },
    downLoadExcel(){
      let buildingName = ''
      if(this.lampIdx == 0){
        switch (this.currentNav){
          case 0:
            buildingName = '全区域汇总'
            break;
          case 1:
            buildingName = '一区汇总'
            break;
          case 2:
            buildingName = '二区汇总'
            break;
          case 3:
            buildingName = '散货汇总'
            break;
        }
      }
      if(this.dateIdx == 0){
        downBlobFile('/api/opt/lamp/exportYearEnergy',{
          buildingName,
        },`${this.buildingName}年报表.xlsx`,'GET')
      }else if(this.dateIdx == 1){
        downBlobFile('/api/opt/lamp/exportMonthEnergy',{
          buildingName,
          startTimeStr: this.startTimeStr,
          endTimeStr: this.endTimeStr
        },`${this.buildingName}月报表.xlsx`,'GET')
      }else{
        downBlobFile('/api/opt/lamp/exportDayEnergy',{
          buildingName,
          startTimeStr: this.startTimeStr,
          endTimeStr: this.endTimeStr
        },`${buildingName}日报表.xlsx`,'GET')
      }
    },
    rBtnHandle(item, idx) {
      this.rIdx = idx;
    },
    isHoliday({ dayjs }){
      return this.holidays.includes(dayjs.format('YYYY-MM-DD'))
    },
    getDayVal({ dayjs }){
      let str = dayjs.format('YYYY-MM-DD');
      return this.holidaysList[str];
    }
  }
};
</script>
<style scop lang="scss">
.down-btn:before {
  content: "\e60d";
}

.energy-time{
  background: red;
  .el-date-table{
    td{
      height: 60px;
    }
  }
  .el-date-range-picker{
    width: 1000px;
  }
  .cell {
    height: 100%;
    padding: 3px 0;
    box-sizing: border-box;
    position: relative;
    cursor: pointer;
  }
  .cell .text {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
  }
  .cell .holiday {
    width: 100%;
    height: calc(100% - 15px);
    //background: var(--el-color-danger);
    color: #000;
    padding-top: 15px;
    cursor: pointer;

    label{
      transform: scale(0.6);
      font-size: 12px;
      cursor: pointer;
    }
  }
}

.lamp-btn-box {
  display: flex;

  .lamp-btn {
    width: 104px;
    height: 42px;
    line-height: 42px;
    text-align: center;
    color: #336666;
    font-size: 16px;
    font-weight: 400;
    margin-right: 2px;
    background: url("@/assets/images/img-area-bg-def.svg") no-repeat left top;
    background-size: 100% 100%;
    cursor: pointer;

    &:hover, &.on {
      background: url("@/assets/images/img-area-bg.svg") no-repeat left top;
      background-size: 100% 100%;
    }
  }
}

.date-box {
  display: flex;
  justify-content: space-between;

  .date-btn-box {
    display: flex;
    margin-top: 10px;
    color: #336666;
  }

  .r-btn {
    display: flex;
  }
}

.echarts-box {
  height: calc(100% - 118px);
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 25px 0 22px;
  margin-top: 10px;

  .name {
    display: flex;
    align-items: center;

    img {
      width: 34px;
      margin-right: 10px;
    }

    div {
      width: 757px;
      height: 47px;
      line-height: 47px;
      background: url("@/assets/images/img-name-bg.png") no-repeat left top;
      background-size: 100% 100%;
      font-size: 20px;
      font-weight: 400;
      color: #004246;
      padding-left: 40px;
    }
  }
}


</style>
